package humanMirror.controller.actions;

import humanMirror.model.controller.Controller;
import humanMirror.model.human.Human;
import humanMirror.service.dbconnection.DBConnection;
import humanMirror.service.dbconnection.SQLiteConnection;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


public class LoginCheckAction implements Action {

	private DBConnection dbConnection = new SQLiteConnection();
	
	private PreparedStatement pstmt = null;
	private Connection conn = null;
	private ResultSet r =null;
	
	public String perform(HttpServletRequest request, HttpServletResponse response){

		String login = request.getParameter("login");
		String password = request.getParameter("password");

		try{
			conn = dbConnection.getConnection();
			
			pstmt = conn.prepareStatement("SELECT * FROM USERS WHERE LOGIN=?1 AND PASSWORD=?2");			
			pstmt.setString(1, login);
			pstmt.setString(2, password);
			pstmt.execute();
			
			r = pstmt.getResultSet();

			if (r.next()) {
				HttpSession session = request.getSession(true);
				session.setAttribute("user", login);
				session.setAttribute("controller", new Controller(new Human()));
				session.setAttribute("questionNumber", 0);
				return "/main.jsp";
			} else {
				request.setAttribute("errorMessage", "Invalid username/password.");
				return "/error.jsp";
			}

		} catch (SQLException e){
			request.setAttribute("errorMessage", e.toString());
			return "/error.jsp";
		} catch (ClassNotFoundException e) {
			request.setAttribute("errorMessage", e.toString());
			return "/error.jsp";
		} finally {

			try {
				pstmt.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}		
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}

		}//finally	
		//return null;
	}//perform
	
	public void setConnection(DBConnection dbConnection){
		this.dbConnection = dbConnection;
	}

}
